# -*- coding: utf-8 -*-
#
# Author:: hanjunfeng
# Date:: 2024/2/29
from logging import getLogger
import traceback


logger = getLogger()


def __get_class_name(currentframe):
    class_name = None
    try:
        self_var = currentframe.f_locals['self']
        class_name = self_var.__class__.__name__
    except KeyError as e:
        logger.error(repr(e))
        logger.error(traceback.format_exc())
    return class_name


def __get_method_name(currentframe):
    method_name = currentframe.f_code.co_name
    return method_name


def get_class_name(currentframe):
    """
    获取当前函数所在的类名
    :param currentframe:
    :return:
    """
    class_name = __get_class_name(currentframe)
    method_name = __get_method_name(currentframe)
    if class_name is None or method_name is None:
        logger.error("仅可在类方法内调用")
        return class_name
    else:
        return class_name


def get_method_name(currentframe):
    """
    获取当前函数名
    :param currentframe:
    :return:
    """
    class_name = __get_class_name(currentframe)
    method_name = __get_method_name(currentframe)
    if class_name is None or method_name is None:
        logger.error("仅可在实例方法内调用")
        return method_name
    else:
        return method_name


if __name__ == "__main__":
    from inspect import currentframe


    class Class1:
        # method_name = get_method_name(currentframe())
        # class_method = get_class_name(currentframe())
        # print(f"method_name:{method_name}")
        # print(f"class_method:{class_method}")

        def __init__(self):
            method_name = get_method_name(currentframe())
            class_method = get_class_name(currentframe())
            print(f"method_name:{method_name}")
            print(f"class_method:{class_method}")

        def method1(self):
            method_name = get_method_name(currentframe())
            class_method = get_class_name(currentframe())
            print(f"method_name:{method_name}")
            print(f"class_method:{class_method}")

        @classmethod
        def method2(cls):
            method_name = get_method_name(currentframe())
            class_method = get_class_name(currentframe())
            print(f"method_name:{method_name}")
            print(f"class_method:{class_method}")


    def function1():
        method_name = get_method_name(currentframe())
        class_method = get_class_name(currentframe())
        print(f"method_name:{method_name}")
        print(f"class_method:{class_method}")


    cls1 = Class1()
    cls1.method1()
    # cls1.method2()
    # Class1.method2()

    # function1()
